package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderListDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.utils.DateUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderListService.class)
@Transactional
public class OrderListServiceImpl implements OrderListService {

    @Resource
    private OrderSettingDao orderSettingDao;
    @Resource
    private MemberDao memberDao;
    @Resource
    private OrderDao orderDao;
    @Resource
    private OrderListDao orderListDao;
    //体检预约
    public Result order(Map map,int[] setmealIds) throws Exception{
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//预约日期
        OrderSetting orderSetting= orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if(orderSetting == null){
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations >= number){
            //已经约满，无法预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String phoneNumber= (String) map.get(" phoneNumber");//获取用户页面输入的手机号
       // System.out.println("手机号："+phoneNumber);
        Member member = memberDao.findByTelephone(phoneNumber);
        if(member != null){
            //判断是否在重复预约
            Integer memberId = member.getId();//会员ID
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约日期
            int setmealId = setmealIds[0];//套餐ID
            Order order = new Order(memberId, order_Date, setmealId);
            //根据条件进行查询
            List<Order> list = orderDao.findByCondition(order);
            if(list != null && list.size() > 0){
                //说明用户在重复预约，无法完成再次预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else{

            //1.如果member 为null；则创建一个member，给其赋值，注册到t_member表中，
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setBirthday(DateUtils.parseString2Date((String) map.get("birthday")));
            member.setSex((String) map.get("sex"));
            member.setIdCard((String) map.get("idCard"));
            member.setPhoneNumber((String) map.get("phoneNumber"));
            member.setFileNumber((String) map.get("idCard"));
            member.setRemark((String) map.get("age"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册

        }

        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(setmealIds[0]);//套餐ID
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        //6、添加预约成功，返回预约order 主键ID
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }


    @Override
    //2. 根据预约ID查询预约相关信息（体检人姓名、预约日期、套餐名称、预约类型）
    public Map findById(Integer id) throws Exception{
        Map map = orderDao.findById4Detail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
        }
        return map;
    }


    @Override
    public PageInfo<Map<String, Object>> findByCondition(QueryPageBean queryPageBean) {
        //3.分页查询
        //分页小助手查询
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<Map<String, Object>> byCondition = orderListDao.findByCondition(queryPageBean);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(byCondition);
        List<Map<String, Object>> list = pageInfo.getList();
        if (list!=null){
            for (Map<String, Object> map : list) {
                //处理日期格式
                Date orderDate = (Date) map.get("orderDate");
                try {
                    map.put("orderDate",DateUtils.parseDate2String(orderDate));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return pageInfo;
    }

    @Override
    public List<Setmeal> findAll() {
        //4.查询所有套餐数据,用于新增预约套餐数据回显
        List<Setmeal> list = orderListDao.findAll();
        return list;
    }

    @Override
    public void updateById(Integer id) {
        //5.用户确认预约，修改用户预约状态
        orderListDao.updateById(id);
    }

    @Override
    public Result deleteById(Integer id) {
        //6.用户取消预约(级联删除)只能取消未到诊）;
        //判断用户预约状态
       String orderStatus= orderListDao.selectorderStatus(id);
       if (orderStatus!=null&&orderStatus.equals("已到诊")){

           // 提示用户不能取消预约
           return new Result(false,"已到诊，不能取消预约！");
       }else {
           //4.1 先查询member_id
           int member_id = orderListDao.selectmember_id(id);
           //4.2 再删除t_order 表(从表)
           orderListDao.deleteById(id);
           //4.3 再删除t_member表(主表)
           orderListDao.deleteBymember_id(member_id);
       }

         return new Result(true,"您已成功取消预约！");
    }
}
